package net.interest.curation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import net.interest.curation.meta.FacebookUserMeta;
import net.interest.curation.model.FacebookUser;
import net.interest.curation.model.User;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;

import scenic3.ScenicPage;
import scenic3.annotation.ActionPath;
import scenic3.annotation.Default;
import scenic3.annotation.Page;

import com.google.gson.stream.JsonWriter;

@Page("/fb")
public class FacebookPage extends ScenicPage {
    private static final Logger log =
        Logger.getLogger(FacebookPage.class.getName());
    
    @ActionPath("newsfeed")
    public Navigation fbnewsfeed() {

        HttpSession session = super.request.getSession();
        User user = (User) session.getAttribute(User.SESSION_USER_ATTR_NAME);
        FacebookUser fbUser = null;
        if (user != null) {
            FacebookUserMeta meta = FacebookUserMeta.get();
            fbUser = Datastore.query(meta).filter(meta.userRef.equal(user.getKey())).asSingle();

        }
        super.response.setContentType("text/json");
        try {

            URL url2 = new URL("https://graph.facebook.com/me/home?access_token=" + fbUser.getAccessToken());
            String response2 = new BufferedReader(new InputStreamReader(url2.openStream())).readLine();
            PrintWriter out = super.response.getWriter();
            out.print(response2);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.severe(e.getLocalizedMessage());
            JsonWriter writer;
            try {
                writer = new JsonWriter(new OutputStreamWriter(super.response.getOutputStream(), "UTF-8"));
                writer.beginObject();
                writer.name("error");
                writer.value(e.getLocalizedMessage());
                writer.close();
            } catch (UnsupportedEncodingException e1) {
                log.severe(e.getLocalizedMessage());
            } catch (IOException e1) {
                log.severe(e.getLocalizedMessage());
           }
            
        }
        return null;
    }

    // /
    @Default
    public Navigation index() {
        if (!isFbOauthExist()) {
            return redirect("/auth/login/fb");
        }
        //return forward("/fb/index.jsp");
        return redirect("/");
    }
    
    private boolean isFbOauthExist() {
        HttpSession session = super.request.getSession();
        User user = (User) session.getAttribute(User.SESSION_USER_ATTR_NAME);
        if (user == null) {
            return false;
        }
        else {
            FacebookUser fbUser = null;
            FacebookUserMeta meta = FacebookUserMeta.get();
            fbUser = Datastore.query(meta).filter(meta.userRef.equal(user.getKey())).asSingle();
           if (fbUser == null) {
                return false;
            }
        }
        return true;
    }
}